package com.android.jingweiapp.activity;

import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.jingweiapp.R;
import com.android.jingweiapp.XMLPhase.AnnounceNewsDetailXMLPhase;
import com.android.jingweiapp.XMLPhase.GetJGOfficeContentXMLPhase;
import com.android.jingweiapp.XMLPhase.GetLeaderDetailXMLPhase;
import com.android.jingweiapp.XMLPhase.GetRegulationContentXMLPhase;
import com.android.jingweiapp.XMLPhase.GetReportContentXMLPhase;
import com.android.jingweiapp.XMLPhase.GetZSDepContentXMLPhase;
import com.android.jingweiapp.XMLPhase.InfoByIdXMLPhase;
import com.android.jingweiapp.adapter.ImageAdapter;
import com.android.jingweiapp.bean.GetNewContent;
import com.android.jingweiapp.bean.LeaderBean;
import com.android.jingweiapp.bean.NewsBean;
import com.android.jingweiapp.bean.OrganizationBean;
import com.android.jingweiapp.util.CommonUtil;
import com.android.jingweiapp.util.Contacts;
import com.android.jingweiapp.util.HttpUtil;
import com.android.jingweiapp.widget.MyToast;
import com.facebook.drawee.view.SimpleDraweeView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 文本新闻
 */
public class DetailTextActivity extends AppCompatActivity {

    @Bind(R.id.btn_back)
    Button btnBack;
    @Bind(R.id.tv_detail_title)
    TextView tvDetailTitle;
    @Bind(R.id.tv_detail_time)
    TextView tvDetailTime;
    @Bind(R.id.tv_detail_from)
    TextView tvDetailFrom;
    @Bind(R.id.tv_detail_content)
    WebView tvDetailContent;
    @Bind(R.id.ly_info)
    RelativeLayout lyInfo;
    @Bind(R.id.pic_viewpager)
    ViewPager picViewpager;


    private ProgressDialog progressDialog;
    private ArrayList<SimpleDraweeView> draweeViews;
    private ImageAdapter imageAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info_detail_text);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        draweeViews = new ArrayList<>();
        imageAdapter = new ImageAdapter(draweeViews);
        picViewpager.setAdapter(imageAdapter);
        progressDialog = ProgressDialog.show(this, "加载中", "请稍后", true, false);
        int type = getIntent().getIntExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS);
        Parcelable beans = getIntent().getParcelableExtra(Contacts.KEY.KEY_OBJECT);
        switch (type) {
            case Contacts.TYPE.TEXT_NEWS:
                getNewsDetail((NewsBean) beans);
                break;
            case Contacts.TYPE.NOTIFY_NEWS:
                getNotifyNewsDetail((NewsBean) beans);
                break;
            case Contacts.TYPE.ANNOUNCE_NEWS:
                getAnnounceNewsDetail((NewsBean) beans);
                break;
            case Contacts.TYPE.LEADER_INFO:
                getLeaderDetail((LeaderBean) beans);
                break;
            case Contacts.TYPE.ORGAN_INFO_OFFICE:
                getOfficeDetail((OrganizationBean.DataEntity) beans);
                break;
            case Contacts.TYPE.ORGAN_INFO_DEP:
                getDepartmentDetail((OrganizationBean.DataEntity) beans);
                break;
            case Contacts.TYPE.REPORT_CONTENT:
                getReportDetail((NewsBean) beans);
                break;
            case Contacts.TYPE.REGULATION_CONTENT:
                getRegulationDetail((NewsBean) beans);
                break;
        }
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    private void getNewsDetail(NewsBean newsBean) {

        tvDetailTitle.setText(newsBean.getTitle());
        tvDetailFrom.setText(newsBean.getFrom());
        tvDetailTime.setText(newsBean.getTime());

        new NewsAsyncTask().execute(newsBean.getId());
    }

    private void getNotifyNewsDetail(NewsBean newsBean) {

        tvDetailTitle.setText(newsBean.getTitle());
        tvDetailFrom.setText(newsBean.getFrom());
        tvDetailTime.setText(newsBean.getTime());

        new NotifyNewsAsyncTask().execute(newsBean.getId());
    }

    private void getAnnounceNewsDetail(NewsBean newsBean) {

        tvDetailTitle.setText(newsBean.getTitle());
        tvDetailFrom.setText(newsBean.getFrom());
        tvDetailTime.setText(newsBean.getTime());

        new AnnounceNewsAsyncTask().execute(newsBean.getId());
    }

    private void getLeaderDetail(LeaderBean leaderBean) {

        tvDetailTitle.setText("主要职责");
        tvDetailFrom.setText(leaderBean.getSource());
        tvDetailTime.setText(leaderBean.getTime());

        new LeaderAsyncTask().execute(leaderBean.getId());
    }

    private void getOfficeDetail(OrganizationBean.DataEntity bean) {

        lyInfo.setVisibility(View.GONE);
        tvDetailTitle.setText(bean.getName());

        new OfficeAsyncTask().execute(bean.getId());
    }

    private void getDepartmentDetail(OrganizationBean.DataEntity bean) {

        lyInfo.setVisibility(View.GONE);
        tvDetailTitle.setText(bean.getName());

        new DepartmentAsyncTask().execute(bean.getId());
    }

    private void getReportDetail(NewsBean newsBean) {

        tvDetailTitle.setText(newsBean.getTitle());
        tvDetailFrom.setText(newsBean.getFrom());
        tvDetailTime.setText(newsBean.getTime());

        new ReportAsyncTask().execute(newsBean.getId());
    }

    private void getRegulationDetail(NewsBean newsBean) {

        tvDetailTitle.setText(newsBean.getTitle());
        tvDetailFrom.setText(newsBean.getFrom());
        tvDetailTime.setText(newsBean.getTime());

        new RegulationAsyncTask().execute(newsBean.getId());
    }


    public void dealData(String result) {
        progressDialog.dismiss();
        if (TextUtils.isEmpty(result)) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        if (result.equals("nodata")) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        tvDetailContent.loadDataWithBaseURL(Contacts.BASE_URL, GetNewContent.getNewContent(result), "text/html", "utf-8", null);
//        tvDetailContent.setText(Html.fromHtml(GetNewContent.getNewContent(result), getImageGetterInstance(), null));


    }

    public void dealData2(String result) {
        progressDialog.dismiss();
        if (TextUtils.isEmpty(result)) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        if (result.equals("nodata")) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        String content = "", picPath = "";
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray jsonArray = jsonObject.getJSONArray("data");

            content = jsonArray.getJSONObject(0).getString("content");//获取新闻内容
            picPath = jsonArray.getJSONObject(0).getString("path");//图片路径
            if (!TextUtils.isEmpty(picPath)) {
                //有图片
                picViewpager.setVisibility(View.VISIBLE);
                setPic(picPath);
            } else {
                picViewpager.setVisibility(View.GONE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        tvDetailContent.loadDataWithBaseURL(Contacts.BASE_URL, GetNewContent.getNewContent(content), "text/html", "utf-8", null);

//        tvDetailContent.setText(Html.fromHtml(GetNewContent.getNewContent(content), getImageGetterInstance(), null));


    }

    private void setPic(String picPath) {
        String[] pics = picPath.split("\\|");
        for (int i = 0; i < pics.length; i++) {
            SimpleDraweeView simpleDraweeView = (SimpleDraweeView) LayoutInflater.from(this).inflate(R.layout.item_adver, null);
            CommonUtil.loadPic(Uri.parse(Contacts.BASE_PIC_URL + pics[i]), simpleDraweeView);
            draweeViews.add(simpleDraweeView);
        }
        imageAdapter.notifyDataSetChanged();

    }

    public void dealReaulationData(String content) throws JSONException {
        progressDialog.dismiss();
        if (TextUtils.isEmpty(content)) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        if (content.equals("nodata")) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        //new JSONObject(content).getJSONArray("data").getJSONObject(0).getString("content");
        String content1 = new JSONObject(content).getJSONArray("data").getJSONObject(0).getString("content");
        tvDetailContent.loadDataWithBaseURL(Contacts.BASE_URL, GetNewContent.getNewContent(content1), "text/html", "utf-8", null);

//        tvDetailContent.setText(Html.fromHtml(GetNewContent.getNewContent(content1), getImageGetterInstance(), null));


    }


    /**
     * ImageGetter用于text图文混排
     *
     * @return
     */
    public Html.ImageGetter getImageGetterInstance() {
        Html.ImageGetter imgGetter = new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                Drawable drawable;
                URL url;
                try {
                    url = new URL(source);
                    drawable = Drawable.createFromStream(url.openStream(), "");//获取网络图片
                } catch (Exception e) {
                    return null;
                }
                int fontH = (int) (getResources().getDimension(
                        R.dimen.textSizeMedium) * 1.5);
                //  int id = Integer.parseInt(source);
                //Drawable d = getResources().getDrawable(id);
                int height = fontH;
                int width = (int) ((float) drawable.getIntrinsicWidth() / (float) drawable
                        .getIntrinsicHeight()) * fontH;
                if (width == 0) {
                    width = drawable.getIntrinsicWidth();
                }
                drawable.setBounds(0, 0, width, height);
                return drawable;
            }
        };
        return imgGetter;
    }


    class NewsAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    InfoByIdXMLPhase.createParam(DetailTextActivity.this, params[0]),
                    new InfoByIdXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData2(str);
        }
    }


    class NotifyNewsAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    AnnounceNewsDetailXMLPhase.createParam(DetailTextActivity.this, params[0]),
                    new AnnounceNewsDetailXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            try {
                dealReaulationData(str);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    class AnnounceNewsAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    AnnounceNewsDetailXMLPhase.createParam(DetailTextActivity.this, params[0]),
                    new AnnounceNewsDetailXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            try {
                dealReaulationData(str);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    class LeaderAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetLeaderDetailXMLPhase.createParam(DetailTextActivity.this, params[0]),
                    new GetLeaderDetailXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }

    class OfficeAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetJGOfficeContentXMLPhase.createParam(DetailTextActivity.this, params[0]),
                    new GetJGOfficeContentXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }

    class DepartmentAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetZSDepContentXMLPhase.createParam(DetailTextActivity.this, params[0]),
                    new GetZSDepContentXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }

    class ReportAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetReportContentXMLPhase.createParam(DetailTextActivity.this, params[0]),
                    new GetReportContentXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }

    class RegulationAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetRegulationContentXMLPhase.createParam(DetailTextActivity.this, params[0]),
                    new GetRegulationContentXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            try {
                dealReaulationData(str);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

}
